﻿namespace Codeplex.Unity.AutoRegister.Config
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// UnityExportAttributeのついた型からRegistTypeTraitを作成するヘルパークラス
    /// </summary>
    public static class AnnotationRegistTypeTraitBuilder
    {
        public static IEnumerable<RegistTypeTrait> Build(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            return BuildCore(type);
        }

        private static IEnumerable<RegistTypeTrait> BuildCore(Type type)
        {
            var annotations = type
                .GetCustomAttributes(typeof(UnityExportAttribute), false)
                .OfType<UnityExportAttribute>();

            foreach (var annotation in annotations)
            {
                var trait = new RegistTypeTrait(type);
                if (annotation.FromType != null)
                {
                    trait.FromType = annotation.FromType;
                }

                if (!string.IsNullOrEmpty(annotation.Name))
                {
                    trait.Name = annotation.Name;
                }

                trait.InjectionMembers = annotation.InjectionMembers;

                if (annotation.LifetimeManager != null)
                {
                    trait.LifetimeManager = annotation.LifetimeManager;
                }

                if (annotation.InjectionMemberProvider != null)
                {
                    trait.InjectionMemberProvider = annotation.InjectionMemberProvider;
                }

                yield return trait;
            }
        }
    }
}
